<template>
	<w-app-container class="app-home">
		<fx-page-header title="员工"></fx-page-header>
		<fxListFilter @resetSearch='resetSearch'>
					<template slot="row-1" >
						<el-form-item label="员工：">
            <!-- <w-select ref='employeeSelect' multiple clearable collapseTags :optionlist='employeeList'>
						</w-select> -->
						<w-select-mulity
							ref='employeeSelect'
							:optionlist="employeeList"
							class="form-input"
						>
						</w-select-mulity>
						</el-form-item>
						<el-form-item label="员工类别：" label-width="110px">
            <!-- <w-select ref='employeeTypeSelect' multiple clearable collapseTags :optionlist='employeeTypeList'>
						</w-select> -->
						<w-select-mulity
							ref='employeeTypeSelect'
							:optionlist="employeeTypeWithAdmin"
							class="form-input"
						>
						</w-select-mulity>
						</el-form-item>
						<el-form-item label="工种：">
            <!-- <w-select ref='workKindSelect' multiple clearable collapseTags :optionlist='workKindList'>
						</w-select> -->
						<w-select-mulity
							ref='workKindSelect'
							:optionlist="workKindList"
							class="form-input"
						>
						</w-select-mulity>
						</el-form-item>
					</template>
					<template slot="row-2" >
						<el-form-item label="启停状态：" label-width="110px">
						<el-select v-model="enableState" prop="enableState" placeholder="请选择" clearable size='mini' class="form-input">
							<el-option
								v-for="item in stateList"
								:key="item.id"
								:label="item.label"
								:value="item.id"
							>
							</el-option>
						</el-select>
						</el-form-item>
					</template>
					<template slot="tools">
						<el-row>
							<el-button type="primary" size='mini' @click="searchStation">查询</el-button>
							<el-button type="text" size='mini' @click="resetSearch">重置</el-button>
						</el-row>
					</template>
		</fxListFilter>
		<w-table
				ref="multipleTable"
				:listData="employeeData"
				:tableColumn="employeeColumns"
				:showPagination="true"
				:showColumnFilterBtn="false"
				minWidth="100px"
				:listTotal="totalCount"
				@on-table-row-dbclick="editRow"
				@on-size-change="handleSizeChange"
				@on-current-change="handleCurrentChange"
				>
				<div slot="btn-tools-right" class="tools-right">
						<el-button type="danger" plain size='mini' @click="mutileDel">删除</el-button>
						<el-button type="success" plain size='mini' @click="mutileEnable">启用</el-button>
						<el-button type="info" plain size='mini' @click="mutileDiable">停用</el-button>
            <el-button type="primary"	size='mini' icon="el-icon-plus">导入员工</el-button>
						<el-button type="primary"	size='mini' icon="el-icon-plus" @click="addEmployee">新建员工</el-button>
				</div>
			</w-table>
		<el-dialog :title="dialogTitle" :visible.sync="employeeInfoDialogVisible" width='480px'  :before-close="beforeClose">
				<div class="create-area">
				<el-form :model="employeeForm" label-position='right' label-width='100px'  :rules="employeeRules" ref="employeeForm" size='mini' style="height:180px;">
						<el-form-item label="员工编号" prop="code" label-width="110px">
								<el-input v-model="employeeForm.code" autocomplete="off" :disabled='isAdmin' class="form-item-input"></el-input>
						</el-form-item>
						<el-form-item label="员工名称" prop="name" label-width="110px">
								<el-input v-model="employeeForm.name" autocomplete="off" :disabled='isAdmin' class="form-item-input"></el-input>
						</el-form-item>
						<el-form-item label="员工类别" prop="employeeType" label-width="110px">
								<w-select :multiple='false' :disabled='isAdmin' v-model="employeeForm.employeeType" :optionlist='employeeTypeList' :isBlock='true' class="form-item-input">
								</w-select>
						</el-form-item>
            <el-form-item label="工种" prop="workKindIds" label-width="110px">
								<el-input autocomplete="off" class="form-item-input">
									<w-icon slot='suffix' class="el-input__icon" type="relation-workkind" size="mini"  @click="handelWorkKind" ></w-icon>
                </el-input>
								<el-tag v-if="employeeForm.workKindIds.length >= 1" style="position:absolute;left:0;">
									{{employeeForm.workKindIds[0].name}}
								</el-tag>
								<el-tag  style="position:absolute;right:80px;" v-if="employeeForm.workKindIds.length > 1">
									+{{employeeForm.workKindIds.length - 1}}
								</el-tag>
						</el-form-item>
						<el-form-item label="用户名" prop="userName" :required="true" label-width="110px" v-if="employeeForm.employeeType === 2">
								<el-input v-model="employeeForm.userName" autocomplete="off" class="form-item-input"></el-input>
						</el-form-item>
						<el-form-item label="密码" prop="passWord" :required="true" label-width="110px" v-if="employeeForm.employeeType === 2">
								<el-input v-model="employeeForm.passWord" autocomplete="off" type="passw" show-password class="form-item-input"></el-input>
						</el-form-item>
						<el-form-item label="启停状态" prop="enable" label-width="110px">
								<el-switch v-model="employeeForm.enable" active-color="#13ce66" :disabled='isAdmin' inactive-color="#ff4949" active-value="1" inactive-value="0"></el-switch>
						</el-form-item>
						<el-form-item label="备注" prop="remark" label-width="110px">
								<el-input
								v-model="employeeForm.remark"
								type="textarea"
								:rows="5"
								:maxlength="200"
								placeholder="请输入备注"
								class="form-item-input"
								show-word-limit
								resize="none"
								:disabled='isAdmin'
							/>
						</el-form-item>
				</el-form>
				</div>
				<div slot="footer" class="dialog-footer">
						<el-button @click="doClose">取 消</el-button>
						<el-button type="primary" @click="doSave('employeeForm')">保 存</el-button>
				</div>
		</el-dialog>
		<transferDialog ref="transferDialog" @on-save-workkind="doSaveWorkKind" :selectStation="selectStation" @on-copy-workkind="copyWorkKind"></transferDialog>
		<fxCopy :hasTree="false" :copyTableData="copyTableData"
			ref="copyDialog"
			:columns="copyWorkKindColumns"
			@on-copysave="copySave">
		</fxCopy>
	</w-app-container>
</template>
<script>
import fxListFilter from '@/components/common/Fx-list-filter.vue'
import fxCopy from '@/components/common/Fx-copy.vue'
import transferDialog from '@/views/station/TransferDialog.vue'
import APP_STATE_CONFIG from '@/config/app_state_config.js'
import FxListStateTag from '@/components/common/Fx-list-state-tag.vue'
export default {
	name: 'station',
	components: {
		fxListFilter,
		fxCopy,
		transferDialog
	},
	data () {
		var checkUserName = (rule, value, callback) => {
			if (!value && this.employeeForm.employeeType === 2) {
				return callback(new Error('用户名不能为空'))
			} else {
				callback()
			}
		}
		var checkPawssord = (rule, value, callback) => {
			if (!value && this.employeeForm.employeeType === 2) {
				return callback(new Error('密码不能为空'))
			} else {
				callback()
			}
		}
		return {
			tableHeight: (document.body.clientHeight - 200) + 'px',
			treeWidth: 220 + 'px',
			treeData: [],
			selTreeNode: '',
			stateList: APP_STATE_CONFIG.enableState,
			employeeList: [],
			employeeTypeWithAdmin: [{
				id: 0,
				name: '系统预置管理员'
			}, {
				id: 1,
				name: '作业人员'
			}, {
				id: 2,
				name: '登录人员'
			}],
			employeeTypeList: [{
				id: 1,
				name: '作业人员'
			}, {
				id: 2,
				name: '登录人员'
			}],
			workKindList: [],
			enableState: '',
			employeeColumns: [
				{ prop: 'code', label: '员工编码', required: true, width: '80px' },
				{ prop: 'name', label: '员工名称', required: true, showOverflowTooltip: true },
				{
					prop: 'employeeType',
					label: '员工类别',
					required: true,
					formatter: this.renderEmployeeType
				},
				{
					prop: 'workKindName',
					label: '工种',
					required: true,
					// formatterIcon: true,
					fxRender: this.iconRender,
					iconType: 'relation-workkind'
				},
				{
					prop: 'enable',
					label: '启停状态',
					required: true,
					fxRender: this.enableRender
				},
				{ prop: 'remark', label: '备注', required: true, showOverflowTooltip: true },
				{
					prop: 'modifyUser', label: '修改人', required: true
				},
				{
					prop: 'modifyDate', label: '修改时间', required: true, showOverflowTooltip: true
				},
				{
					prop: 'createUser', label: '创建人', required: true
				},
				{
					prop: 'createDate', label: '创建时间', required: true, showOverflowTooltip: true
				}
			],
			totalCount: 0,
			employeeData: [],
			employeeInfoDialogVisible: false,
			dialogTitle: '',
			employeeForm: {
				code: '',
				name: '',
				employeeType: '',
				userName: '',
				passWord: '',
				workKindIds: [],
				enable: '1',
				remark: ''
			},
			employeeRules: {
				code: [
					{ required: true, message: '请输入员工编号', trigger: 'change' },
					{ min: 1, max: 18, message: '长度最多18个字符', trigger: 'blur' }
				],
				name: [
					{ required: true, message: '请输入员工名称', trigger: 'change' },
					{ min: 1, max: 50, message: '长度最多50个字符', trigger: 'blur' }
				],
				userName: [
					{ validator: checkUserName, trigger: 'blur' },
					{ min: 1, max: 20, message: '长度最多20个字符', trigger: 'blur' }
				],
				passWord: [
					{ validator: checkPawssord, trigger: 'blur' },
					{ min: 1, max: 8, message: '长度最多8个字符', trigger: 'blur' }
				],
				remark: [
					{ min: 1, max: 200, message: '长度最多200个字符', trigger: 'blur' }
				]
			},
			fxDataVerification: null,
			selectStation: '',
			editWorkKind: false,
			copyInfoDialogVisible: false,
			copyTableData: [],
			copyType: '',
			copyWorkKindColumns: [{
				label: '员工编号',
				prop: 'code',
				width: '100px',
				required: true
			}, {
				label: '员工名称',
				prop: 'name',
				width: '120px',
				required: true
			}, {
				label: '员工类型',
				prop: 'employeeType',
				width: '120px',
				required: true,
				formatter: row => row.employeeType === 1 ? '作业人员' : '登录人员'
			}]
		}
	},
	created () {
		// 获取员工下拉选择项
		this.getEmployeeList()
		this.getWorkKindList()
		this.onRefreshEmployeeList()
	},
	computed: {
		enableFormaterState (val, key) {
			return (val, key) => {
				return this.$fxStateMiddleware.getStateObj('enableState')(val)[key]
			}
		},
		isAdmin () {
			return this.employeeForm.employeeType === 0
		}
	},
	methods: {
		getEmployeeList () {
			this.getAllEmployeeList().then(res => {
				this.employeeList = res
			})
		},
		// 获取员工下拉选择数据
		getAllEmployeeList () {
			return new Promise(resolve => {
				this.$fxApi('employee.findListAll').then(res => {
					resolve(res)
				})
			})
		},
		// 获取工种
		getWorkKindList () {
			return new Promise(resolve => {
				this.$fxApi('workKind.getWorkKindListAll').then(res => {
					this.workKindList = res
					resolve(res)
				})
			})
		},
		getAllStationType (row) {
			return new Promise(resolve => {
				const employeeTypeList = [{
					id: 1,
					name: '作业人员'
				}, {
					id: 2,
					name: '登录人员'
				}]
				if (row && row.employeeType === 0) {
					employeeTypeList.push({
						id: 0,
						name: '系统预置管理员'
					})
				}
				resolve(employeeTypeList)
			})
		},
		// 列表数据
		onRefreshEmployeeList () {
			this.selstationCount = 0
			const searchParams = {
				pageNum: (this.$refs.multipleTable && this.$refs.multipleTable.getPaginationParams().pageNum) || 1,
				pageSize: (this.$refs.multipleTable && this.$refs.multipleTable.getPaginationParams().pageSize) || 20
			}
			var params = {}
			if (this.enableState !== '') {
				params.enable = this.enableState
			}
			// 员工下拉
			if (this.$refs.employeeSelect && this.$refs.employeeSelect.currentValue.length >= 1) {
				params.employeeIds = this.$refs.employeeSelect.currentValue
			}
			// 员工类别下拉
			if (this.$refs.employeeTypeSelect && this.$refs.employeeTypeSelect.currentValue.length >= 1) {
				params.employeeTypes = this.$refs.employeeTypeSelect.currentValue
			}
			// 工种下拉
			if (this.$refs.workKindSelect && this.$refs.workKindSelect.currentValue.length >= 1) {
				params.workKindIds = this.$refs.workKindSelect.currentValue
			}
			if (Object.keys(params).length !== 0) {
				searchParams.params = params
			}
			return new Promise(resolve => {
				this.$fxApi('employee.findAllEmployee')({
					data: searchParams
				}).then(res => {
					this.totalCount = this.$fxUtils.toNumber(res.total)
					this.employeeData = res.data
					// this.$refs.multipleTable.clearSelected()
					resolve()
				})
			})
		},
		handleSizeChange (val) {
			this.onRefreshEmployeeList()
		},
		handleCurrentChange (val) {
			this.onRefreshEmployeeList()
		},
		addEmployee () {
			this.editWorkKind = false
			this.selectStation = ''
			return new Promise(resolve => {
				Promise.all([
					this.getAllStationType(),
					this.getNextCode()
				]).then(([shoplist, newCode]) => {
					this.employeeTypeList = shoplist
					this.showDialog(newCode)
					resolve()
				})
			})
		},
		showDialog (code) {
			this.employeeInfoDialogVisible = true
			if (this.$refs.employeeForm) {
				this.$refs.employeeForm.resetFields()
			}
			Object.keys(this.employeeForm).map(m => {
				this.employeeForm[m] = ''
			})
			this.employeeForm.code = code
			this.employeeForm.workKindIds = []
			this.employeeForm.employeeType = 1
			this.employeeForm.enable = '1'
			this.fxDataVerification = this.$fxUtils.fxDataVerification(this.employeeForm)
			this.dialogTitle = '新建员工'
		},
		renderEmployeeInfo (res) {
			const { code, id, employeeType, enable, name, remark, userName, passWord } = res
			this.employeeForm = {
				code,
				id,
				employeeType,
				enable,
				name,
				remark,
				userName,
				passWord
			}
			this.employeeForm.workKindIds = res.workKindEntityList ? res.workKindEntityList : []
			this.employeeForm.enable = res.enable ? '1' : '0'
			this.fxDataVerification = this.$fxUtils.fxDataVerification(this.employeeForm)
		},
		doClose () {
			this.VerityCompanyData()
		},
		beforeClose () {
			this.VerityCompanyData()
		},
		VerityCompanyData () {
			const isChange = !this.fxDataVerification.checkData(this.employeeForm)
			if (isChange) {
				this.$fxCommon.orderListFrontFunc('VeritybeforeClose').then(() => {
					this.doSave('employeeForm')
				}).catch(() => {
					this.employeeInfoDialogVisible = false
				})
				return false
			} else {
				this.employeeInfoDialogVisible = false
			}
		},
		doSave (formName) {
			this.$refs[formName].validate((valid) => {
				if (valid) {
					this.saveOrUpdateEmployee().then(this.$fxCommon.orderSuccess('save')).then(() => {
						this.employeeInfoDialogVisible = false
						this.onRefreshEmployeeList().then(this.getEmployeeList)
					})
				} else {
					return false
				}
			})
		},
		editRow (row, column, event) {
			this.editWorkKind = false
			this.selectStation = row.id
			this.dialogTitle = '修改员工'
			return new Promise(resolve => {
				Promise.all([
					this.getAllStationType(row),
					this.findGroupDetailById(row)
				]).then(([shoplist, detail]) => {
					this.employeeTypeList = shoplist
					this.employeeInfoDialogVisible = true
					this.renderEmployeeInfo(detail)
					resolve()
				})
			})
		},
		editRowWorkKind (row) {
			this.editWorkKind = true
			return new Promise(resolve => {
				Promise.all([
					this.getAllStationType(row),
					this.findGroupDetailById(row)
				]).then(([shoplist, detail]) => {
					this.employeeTypeList = shoplist
					this.renderEmployeeInfo(detail)
					this.handelWorkKind(row)
					resolve()
				})
			})
		},
		// 批量删除
		mutileDel () {
			const _selData = this.$refs.multipleTable.selectedRowArr
			return this.$fxCommon.orderListFrontFunc('deleteMulity', _selData)
				.then(this.deleteEmployee)
				.then(this.$fxCommon.orderSuccess('deleteMulity'))
				.then(this.onRefreshEmployeeList)
		},
		// 批量启用
		mutileEnable () {
			const _selData = this.$refs.multipleTable.selectedRowArr
			return this.$fxCommon.orderListFrontFunc('enableMulity', _selData).then(() => {
				this.handleState(1).then(this.$fxCommon.orderSuccess('enableMulity')).then(this.onRefreshEmployeeList)
			})
		},
		// 批量停用
		mutileDiable () {
			const _selData = this.$refs.multipleTable.selectedRowArr
			return this.$fxCommon.orderListFrontFunc('disableMulity', _selData).then(() => {
				this.handleState(0).then(this.$fxCommon.orderSuccess('disableMulity')).then(this.onRefreshEmployeeList)
			})
		},
		// 启用 停用
		handleState (type) {
			const _selData = this.$refs.multipleTable.selectedRowArr
			const ids = _selData.map(station => station.id)
			return new Promise(resolve => {
				this.$fxApi('employee.updateEnables')({
					data: {
						employeeIds: ids,
						enable: type
					}
				}).then(res => {
					resolve(res)
				})
			})
		},
		resetSearch () {
			this.enableState = ''
			this.$refs.employeeSelect.currentValue = []
			this.$refs.employeeTypeSelect.currentValue = []
			this.$refs.workKindSelect.currentValue = []
		},
		// 查询集团
		searchStation () {
			this.onRefreshEmployeeList()
		},
		// 获取编号
		getNextCode () {
			return new Promise(resolve => {
				this.$fxApi('employee.getNextCode').then(res => {
					resolve(res)
				})
			})
		},
		// 获取员工信息
		findGroupDetailById (row) {
			return new Promise(resolve => {
				this.$fxApi('employee.findEmployeeDetailById')({
					query: {
						id: row.id
					}
				}).then(res => {
					resolve(res)
				})
			})
		},
		// 新建更新员工信息
		saveOrUpdateEmployee () {
			const { code, id, enable, name, remark, employeeType, userName, passWord } = this.employeeForm
			const postData = {
				id,
				code,
				enable,
				name,
				remark,
				employeeType,
				userName,
				passWord
			}
			// 所属工种
			if (this.employeeForm.workKindIds) {
				postData.workKindIds = this.employeeForm.workKindIds.map(s => {
					return s.id
				})
			}
			return new Promise(resolve => {
				this.$fxApi('employee.saveOrUpdate')({
					data: postData
				}).then(res => {
					resolve(res)
				})
			})
		},
		// 删除员工信息
		deleteEmployee () {
			const _selData = this.$refs.multipleTable.selectedRowArr
			const ids = []
			_selData.forEach((v) => {
				ids.push(v.id)
			})
			return new Promise(resolve => {
				this.$fxApi('employee.deleteEmployeeMulity')({
					data: {
						employeeIds: ids
					}
				}).then(res => {
					resolve(res)
				})
			})
		},
		handelWorkKind (row) {
			if (row.id) {
				this.selectStation = row.id ? row.id : ''
			}
			const id = this.employeeForm.id || this.selectStation
			this.$refs.transferDialog.open(id, this.employeeForm.workKindIds)
		},
		doSaveWorkKind (selKinds) {
			this.employeeForm.workKindIds = selKinds
			this.$forceUpdate()
			if (this.editWorkKind) {
				this.saveOrUpdateEmployee().then(this.$fxCommon.orderSuccess('save')).then(() => {
					this.onRefreshEmployeeList()
				})
			}
		},
		// 复制工种关系
		copyWorkKind () {
			this.copyTableData = []
			this.copyEmployeeList(this.employeeForm.id).then(res => {
				this.copyTableData = res
				this.copyTotalCount = res.length
				this.$refs.copyDialog.open()
			})
		},
		// 复制 右侧工位列表
		copyEmployeeList (id) {
			return new Promise(resolve => {
				this.$fxApi('employee.copyGetAllEmployee')({
					query: {
						id: id
					}
				}).then(res => {
					resolve(res)
				})
			})
		},
		copySave (selData, busType) {
			this.copyType = busType
			return this.$fxCommon.orderListFrontFunc('copyMulity', selData)
				.then(this.doCopySave)
				.then(this.$fxCommon.orderSuccess('copyMulity'))
				.then(this.closeDialog)
				.then(this.onRefreshEmployeeList)
		},
		closeDialog () {
			this.$refs.copyDialog.onCancelClick()
		},
		doCopySave (data) {
			const copyIds = data.map(d => {
				return d.id
			})
			return new Promise(resolve => {
				this.$fxApi('employee.fromEmployeeTocopyRelation')({
					data: {
						operType: this.copyType,
						copyId: copyIds,
						currentId: this.employeeForm.id
					}
				}).then(res => {
					resolve(res)
				})
			})
		},
		enableRender (h, { row }) {
			return <FxListStateTag
				icon={this.enableFormaterState(row.enable, 'icon')}
				label={this.enableFormaterState(row.enable, 'label')}
			></FxListStateTag>
		},
		iconRender (h, { row }) {
			return <w-icon
				slot='icon-slot' type='relation-workkind'
				size="mini"
				rowInfo={row}
				vOn:click={this.editRowWorkKind}
			></w-icon>
		},
		renderEmployeeType (row) {
			switch (row.employeeType) {
			case 0:
				return '系统预置管理员'
			case 1:
				return '作业人员'
			case 2:
				return '登录人员'
			default:
				return ''
			}
		}
	}
}
</script>
<style lang="stylus" scoped>
@import '~$assets/stylus/varsty.styl'
.create-area {
	width: 100%
	height: 400px
	box-sizing: border-box
	.form-item-input {
		width:280px
	}
}
.form-input {
	width: 170px
}
</style>
